package com.dotstone.chipism.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.activity.CaptureActivity;
import com.dotstone.chipism.activity.DeviceStateActivity;
import com.dotstone.chipism.activity.EarnMoneyActivity;
import com.dotstone.chipism.activity.FirstSetupActivity1;
import com.dotstone.chipism.activity.GroupListActivity;
import com.dotstone.chipism.activity.LingHuoSwitchActivity;
import com.dotstone.chipism.activity.RemoteAirActivity;
import com.dotstone.chipism.activity.RemoteSocketActivity1;
import com.dotstone.chipism.activity.RemoteSwitchActivity1;
import com.dotstone.chipism.activity.SocketActivity;
import com.dotstone.chipism.adapter.TaskAdapter;
import com.dotstone.chipism.ui.curtain.RemoteCurtainActivity;
import com.dotstone.chipism.ui.login.LoginActivity;
import com.dotstone.chipism.activity.MainActivity;
import com.dotstone.chipism.activity.MainActivity.OnDataUpdateListener;
import com.dotstone.chipism.activity.PublishOrderActivity;
import com.dotstone.chipism.activity.RemoteAirActivity1;
import com.dotstone.chipism.activity.RemoteAirActivity2;
import com.dotstone.chipism.activity.RemoteBoxActivity;
import com.dotstone.chipism.activity.RemoteDVDActivity;
import com.dotstone.chipism.activity.RemoteFanActivity;
import com.dotstone.chipism.activity.RemoteProjectActivity;
import com.dotstone.chipism.activity.RemoteRGBLightActivity;
import com.dotstone.chipism.activity.RemoteSatelliteActivity;
import com.dotstone.chipism.activity.RemoteSocketActivity;
import com.dotstone.chipism.activity.RemoteSwitchActivity;
import com.dotstone.chipism.activity.RemoteTVActivity;
import com.dotstone.chipism.activity.SceneListActivity;
import com.dotstone.chipism.activity.ShareTargetActivity;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.DeviceType;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.Key;
import com.dotstone.chipism.bean.Room;
import com.dotstone.chipism.bean.Scene;
import com.dotstone.chipism.bean.Scene_Task;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.listener.NavigationBarChangedListener;
import com.dotstone.chipism.listener.onReachTopListener;
import com.dotstone.chipism.recycleview.ADInfo;
import com.dotstone.chipism.recycleview.CycleViewPager;
import com.dotstone.chipism.recycleview.CycleViewPager.ImageCycleViewListener;
import com.dotstone.chipism.recycleview.ViewFactory;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.MyDBHelper;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.BaseAnimatorSet;
import com.dotstone.chipism.view.BlurBehind;
import com.dotstone.chipism.view.CicleDeviceLayout;
import com.dotstone.chipism.view.CicleDeviceLayout.OnDeviceItemClickListener1;
import com.dotstone.chipism.view.CicleGroupLayout;
import com.dotstone.chipism.view.CicleGroupLayout.OnAddRoomListener;
import com.dotstone.chipism.view.CicleMenuLayoutBlue;
import com.dotstone.chipism.view.CicleMenuLayoutBlue.OnAddSceneListener;
import com.dotstone.chipism.view.CicleMenuLayoutBlue.OnMenuItemClickListener1;
import com.dotstone.chipism.view.MyLinearLayout;
import com.dotstone.chipism.view.NormalDialog;
import com.dotstone.chipism.view.OnBlurCompleteListener;
import com.dotstone.chipism.view.OnBtnClickL;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainFragment extends Fragment
		implements OnClickListener, OnRequestPermissionsResultCallback {
	public static MainFragment instance;
	private TextView mLoadingTv;
	private RelativeLayout empty_rl;
	private LinearLayout layout1;
	private LinearLayout layout2;
	private LinearLayout mScanBtn;
	private LinearLayout mShareBtn;
	private LinearLayout mEarnBtn;
	private LinearLayout mServiceBtn;
	private LinearLayout mBrandLayout;
	private Button mDeviceStatusBtn;
	private LinearLayout mTabBtn;
	private Button mGetDeviceB;
	private Button mSetupB;
	private TextView mStatusTv;
	private CicleMenuLayoutBlue mSceneC;
	private CicleDeviceLayout mDeviceCircle;
	private CicleGroupLayout mRoomC;
	private CycleViewPager cycleViewPager;
	private List<Device> mDevices = new ArrayList<Device>();
	private List<Room> mRooms = new ArrayList<Room>();
	private List<Scene> mScenes = new ArrayList<Scene>();
	private List<ImageView> views = new ArrayList<ImageView>();
	private List<ADInfo> infos = new ArrayList<ADInfo>();
	private String[] imageUrls = { "http://img.taodiantong.cn/v55183/infoimg/2013-07/130720115322ky.jpg",
			"http://pic30.nipic.com/20130626/8174275_085522448172_2.jpg",
			"http://pic18.nipic.com/20111215/577405_080531548148_2.jpg",
			"http://pic15.nipic.com/20110722/2912365_092519919000_2.jpg",
			"http://pic.58pic.com/58pic/12/64/27/55U58PICrdX.jpg" };
	private int[] imageRes = { R.drawable.guanggao1, R.drawable.guanggao2, R.drawable.guanggao3, R.drawable.guanggao4,
			R.drawable.guanggao5 };

	private static final int GET_DEVICE_SUCCESS = 0;
	private static final int GET_DEVICE_FAIL = 1;
	private static final int GET_SCENE_SUCCESS = 2;
	private static final int GET_ROOM_SUCCESS = 3;
	private static final int GET_PERMISSION_SUCCESS = 4;
	private static final int GET_SCENE_FINISH = 5;
	public static NormalDialog mNormalDialog;
	public static BaseAnimatorSet bas_in;
	public static  BaseAnimatorSet bas_out;
	private boolean isSceneShow = true;
	private SVProgressHUD mSvProgressHUD;
	private boolean layout2Show = false;
	private MyLinearLayout myLinearLayout;
	private boolean adapter = false;
	public boolean hasOrder = false;
	private MyDBHelper myDBHelper;

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		instance = this;
		View view = inflater.inflate(R.layout.fragment_main, container, false);
		findView(view);
		initEvent();
		configImageLoader();
		initialize();
		mSvProgressHUD = new SVProgressHUD(getActivity());
		myDBHelper = new MyDBHelper(getActivity());
		MainActivity.mainActivity.setDataUpdateLiistener(new OnDataUpdateListener() {

			@Override
			public void update(int count1, int count2) {
				// TODO Auto-generated method stub
				mDevices = DeviceManager.getInstance().getAllDevice();
				if (DeviceManager.getInstance().getAllDevice().size() > 0) {
					mLoadingTv.setVisibility(View.GONE);
					layout1.setVisibility(View.VISIBLE);
					empty_rl.setVisibility(View.GONE);
					layout2.setVisibility(View.GONE);
					layout2Show = false;
					mStatusTv.setText("全局状态：          数量：" + mDevices.size() + " 在线：" + mDevices.size());
				} else {
					mLoadingTv.setVisibility(View.GONE);
					layout1.setVisibility(View.GONE);
					empty_rl.setVisibility(View.VISIBLE);
					layout2.setVisibility(View.VISIBLE);
					layout2Show = true;
					mStatusTv.setText("全局状态：          数量：" + mDevices.size() + " 在线：" + mDevices.size());
				}
			}
		});
		return view;
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 请求设备数据 根据是否存在数据展示控件
		Log.i("nav", "onResume");
		if (!DeviceManager.getInstance().hid.equals("")) {
			getAllDevice();
			getAllScene();
		}
		// 检查DeviceManager的设备
		// 如果已经有设备
		// 则直接展示转盘的layout
		if (layout2Show) {
			Log.i("wmy", "设备不为空，隐藏layout1");
			layout1.setVisibility(View.GONE);
			layout2.setVisibility(View.VISIBLE);
		}
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				checkNavigationBar();
			}
		}, 500);
		// checkShop(); // 检查是否有商城订单
		// check();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.i("nav", "onPause");
	}

	private void findView(View view) {
		// TODO Auto-generated method stub
		mLoadingTv = (TextView) view.findViewById(R.id.loading_tv);
		empty_rl = (RelativeLayout) view.findViewById(R.id.empty_rl);
		layout1 = (LinearLayout) view.findViewById(R.id.layout1);
		layout2 = (LinearLayout) view.findViewById(R.id.layout2);
		mScanBtn = (LinearLayout) view.findViewById(R.id.scan_layout);
		mShareBtn = (LinearLayout) view.findViewById(R.id.share_layout);
		mEarnBtn = (LinearLayout) view.findViewById(R.id.earn_layout);
		mServiceBtn = (LinearLayout) view.findViewById(R.id.service_layout);
		mDeviceStatusBtn = (Button) view.findViewById(R.id.setting_btn);
		mTabBtn = (LinearLayout) view.findViewById(R.id.tab_btn);
		mGetDeviceB = (Button) view.findViewById(R.id.get_free_btn);
		mSetupB = (Button) view.findViewById(R.id.first_btn);
		mStatusTv = (TextView) view.findViewById(R.id.device_status_tv);
		mRoomC = (CicleGroupLayout) view.findViewById(R.id.roomlayout);
		mSceneC = (CicleMenuLayoutBlue) view.findViewById(R.id.scenelayout);
		mDeviceCircle = (CicleDeviceLayout) view.findViewById(R.id.id_devicelayout);
		myLinearLayout = (MyLinearLayout) view.findViewById(R.id.my_layout);
		mBrandLayout = (LinearLayout) view.findViewById(R.id.brand);
		mSceneC.addMenus();
		mSceneC.setScenes(mScenes);
		mDeviceCircle.addMenus();
		mRoomC.addMenus();
		mRoomC.setRooms(mRooms);
	}

	private void initEvent() {
		mScanBtn.setOnClickListener(this);
		mShareBtn.setOnClickListener(this);
		mEarnBtn.setOnClickListener(this);
		mServiceBtn.setOnClickListener(this);
		mDeviceStatusBtn.setOnClickListener(this);
		mTabBtn.setOnClickListener(this);
		mGetDeviceB.setOnClickListener(this);
		mSetupB.setOnClickListener(this);
		mRoomC.setOnReachTopListener(new onReachTopListener() {

			@Override
			public void reach(String id) {
				// TODO Auto-generated method stub
				Log.e("circle", "组别到顶了 = " + id);
				if (DeviceManager.getInstance().getRoomById(id) != null) {
					List<Device> devices = DeviceManager.getInstance().getGroupChildDevicesById(id);
					List<Device> devices1 = DeviceManager.getInstance().getGroupChildDevicesById1(id);
					if (devices != null) {
						Log.i("circle", "到顶的组别是 " + DeviceManager.getInstance().getRoomById(id).getRoomName()
								+ " devices.size() = " + devices.size() + " devices1 = " + devices1.size());
					} else {
						Log.i("circle", "到顶的组别是 " + DeviceManager.getInstance().getRoomById(id).getRoomName()
								+ " devices.size() = 为空");
					}
					mDeviceCircle.setDevices(devices);
				} else {
					Log.i("circle", "到顶的组别为空");
					List<Device> devices = new ArrayList<Device>();
					mDeviceCircle.setDevices(devices);
				}
			}
		});

		mSceneC.setOnReachTopListener(new onReachTopListener() {

			@Override
			public void reach(String id) {
				// TODO Auto-generated method stub
				Log.e("circle", "情景到顶了 = " + id);
				if (DeviceManager.getInstance().getSceneById(id) != null) {
					List<Device> devices = DeviceManager.getInstance().getSceneChildDevicesById(id);
					// List<Device> devices = new ArrayList<Device>();
					// for (Scene s : mScenes) {
					// if (s.getSceneId().equals(id)) {
					// devices = s.getDevices();
					if (devices != null) {
						Log.i("circle", "到顶的情景是 " + DeviceManager.getInstance().getSceneById(id).getSceneName()
								+ " devices.size() = " + devices.size());
					} else {
						Log.i("circle", "到顶的情景是 " + DeviceManager.getInstance().getSceneById(id).getSceneName()
								+ " devices.size() = 为空");
					}
					mDeviceCircle.setDevices(devices);
				} else {
					List<Device> devices = new ArrayList<Device>();
					mDeviceCircle.setDevices(devices);
				}
			}
		});
		mRoomC.setOnAddRoomListener(new OnAddRoomListener() {

			@Override
			public void addClick() {
				// TODO Auto-generated method stub
				BlurBehind.getInstance().execute(MainActivity.mainActivity, new OnBlurCompleteListener() {
					@Override
					public void onBlurComplete() {
						Intent intent = new Intent(getActivity(), GroupListActivity.class);
						intent.putExtra("position", -1);
						intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
						startActivity(intent);
					}
				});
			}
		});
		mSceneC.setmAddSceneListener(new OnAddSceneListener() {

			@Override
			public void addClick() {
				// TODO Auto-generated method stub
				BlurBehind.getInstance().execute(MainActivity.mainActivity, new OnBlurCompleteListener() {
					@Override
					public void onBlurComplete() {
						Intent intent = new Intent(getActivity(), SceneListActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
						startActivity(intent);
					}
				});
			}
		});
		mSceneC.setOnMenuItemClickListener(new OnMenuItemClickListener1() {

			@Override
			public void itemClick(String id) {
				// TODO Auto-generated method stub
				Scene s = DeviceManager.getInstance().getSceneById(id);
				Log.i("wmy", "点击了 id= " + id + " " + s.getSceneName());
				if (s != null) {
					// getPermission(id, 1);
					showOpenSceneDialog(id);
				}
			}
		});
		mDeviceCircle.setOnDeviceItemClickListener(new OnDeviceItemClickListener1() {

			@Override
			public void itemClick(String id) {
				// TODO Auto-generated method stub
				// 通过Id 获取当前开关状态以及设备
				// 再根据其网关发送开关指令
				Device d = DeviceManager.getInstance().getDeviceById(id);
				if (d == null) {
					return;
				}
				switch (d.getDeviceType()) {

					case DeviceType.LINGHUO_SWITCH_1://一键零火开关
					Intent	intent123 = new Intent(getActivity(), LingHuoSwitchActivity.class);
						DeviceManager.getInstance().setmWlanId(d.getMainDeviceId());
						intent123.putExtra("address",d.getDeviceAddress());
						intent123.putExtra("deviceid", d.getDeviceID());
						intent123.putExtra("devicetype",d.getDeviceType());
						startActivity(intent123);
						break;
					case DeviceType.LINGHUO_SWITCH_2://2键零火开关
						Intent	intent1234 = new Intent(getActivity(), LingHuoSwitchActivity.class);
						DeviceManager.getInstance().setmWlanId(d.getMainDeviceId());
						intent1234.putExtra("address",d.getDeviceAddress());
						intent1234.putExtra("deviceid", d.getDeviceID());
						intent1234.putExtra("devicetype",d.getDeviceType());
						startActivity(intent1234);
						break;
					case DeviceType.LINGHUO_SWITCH_3://3键零火开关
						Intent	intent12345 = new Intent(getActivity(), LingHuoSwitchActivity.class);
						DeviceManager.getInstance().setmWlanId(d.getMainDeviceId());
						intent12345.putExtra("address",d.getDeviceAddress());
						intent12345.putExtra("deviceid", d.getDeviceID());
						intent12345.putExtra("devicetype",d.getDeviceType());
						startActivity(intent12345);
						break;
				case DeviceType.DEVICE_TYPE_RGB_LIGHT:
					Intent intent = new Intent(getActivity(), RemoteRGBLightActivity.class);
					DeviceManager.getInstance().setmWlanId(d.getMainDeviceId());
					intent.putExtra("address", d.getDeviceAddress());
					intent.putExtra("id", id);
					startActivity(intent);
					break;
					case DeviceType.DEVICE_TYPE_CHAZUO:
						Intent intent11 = new Intent(getActivity(), SocketActivity.class);
						intent11.putExtra("address", d.getDeviceAddress());
						DeviceManager.getInstance().setmWlanId(d.getMainDeviceId());
						intent11.putExtra("id", id);
						intent11.putExtra("deviceid", d.getDeviceID());
						startActivity(intent11);
						break;
				case DeviceType.DEVICE_TYPE_SOCKET:
					Intent intent1 = new Intent(getActivity(), RemoteSocketActivity1.class);
					intent1.putExtra("address", d.getDeviceAddress());
					DeviceManager.getInstance().setmWlanId(d.getMainDeviceId());
					intent1.putExtra("id", id);
					intent1.putExtra("deviceid", d.getDeviceID());
					startActivity(intent1);
					break;
					case DeviceType.DEVICE_TYPE_CURTAIN:
						Intent intent222 = new Intent(getActivity(), RemoteCurtainActivity.class);
						intent222.putExtra("address", d.getDeviceAddress());
						DeviceManager.getInstance().setmWlanId(d.getMainDeviceId());
						intent222.putExtra("id", id);
						intent222.putExtra("deviceid", d.getDeviceID());
						startActivity(intent222);
						break;
				case DeviceType.DEVICE_TYPE_SWITCH:
					Intent intent2 = new Intent(getActivity(), RemoteSwitchActivity1.class);
					intent2.putExtra("address", d.getDeviceAddress());
					DeviceManager.getInstance().setmWlanId(d.getMainDeviceId());
					intent2.putExtra("id", id);
					startActivity(intent2);
					break;
				case DeviceType.DEVICE_TYPE_DVD:
					Intent intent12 = new Intent(getActivity(), RemoteDVDActivity.class);
					DeviceManager.getInstance().setmWlanId(d.getMainDeviceId());
					intent12.putExtra("position", -1);
					intent12.putExtra("id", id);
					startActivity(intent12);
					break;
				case DeviceType.DEVICE_TYPE_PROJECTOR:
					Intent intent3 = new Intent(getActivity(), RemoteProjectActivity.class);
					DeviceManager.getInstance().setmWlanId(d.getMainDeviceId());
					intent3.putExtra("position", -1);
					intent3.putExtra("id", id);
					startActivity(intent3);
					break;
				case DeviceType.DEVICE_TYPE_TV:
					Intent intent4 = new Intent(getActivity(), RemoteTVActivity.class);
					DeviceManager.getInstance().setmWlanId(d.getMainDeviceId());
					intent4.putExtra("position", -1);
					intent4.putExtra("id", id);
					startActivity(intent4);
					break;
				case DeviceType.DEVICE_TYPE_FAN:
					Intent intent5 = new Intent(getActivity(), RemoteFanActivity.class);
					DeviceManager.getInstance().setmWlanId(d.getMainDeviceId());
					intent5.putExtra("position", -1);
					intent5.putExtra("id", id);
					startActivity(intent5);
					break;
				case DeviceType.DEVICE_TYPE_SATELLITE:
					Intent intent6 = new Intent(getActivity(), RemoteSatelliteActivity.class);
					DeviceManager.getInstance().setmWlanId(d.getMainDeviceId());
					intent6.putExtra("position", -1);
					intent6.putExtra("id", id);
					startActivity(intent6);
					break;
				case DeviceType.DEVICE_TYPE_BOX2:
					Intent intent7 = new Intent(getActivity(), RemoteBoxActivity.class);
					DeviceManager.getInstance().setmWlanId(d.getMainDeviceId());
					intent7.putExtra("position", -1);
					intent7.putExtra("id", id);
					startActivity(intent7);
					break;
				case DeviceType.DEVICE_TYPE_AIR_CONTROLLER:
					DeviceManager.getInstance().setmWlanId(d.getMainDeviceId());
					if (d.getDeviceBrand() != null && !d.getDeviceBrand().equals("")) {
						if (d.getDeviceBrand().length() == 16) {
							Intent intent9 = new Intent(getActivity(), RemoteAirActivity1.class);
							intent9.putExtra("position", -1);
							intent9.putExtra("id", id);
							intent9.putExtra("deviceModel", d.getDeviceBrand());
							Log.i("wmy", getClass().getSimpleName() + " deviceModel = " + d.getDeviceBrand());
							startActivity(intent9);
						} else {
							Intent intent221 = new Intent(getActivity(), RemoteAirActivity2.class);
							intent221.putExtra("position", -1);
							intent221.putExtra("id", id);
							intent221.putExtra("deviceModel", d.getDeviceBrand());
							startActivity(intent221);
						}
					} else {
						String model = d.getDeviceBrand();
						if (model != null && !model.equals("")) {
							if (model.length() == 16) {
								Intent intent9 = new Intent(getActivity(), RemoteAirActivity1.class);
								intent9.putExtra("position", -1);
								intent9.putExtra("id", id);
								intent9.putExtra("deviceModel", model);
								Log.i("wmy", getClass().getSimpleName() + " deviceModel = " + model);
								startActivity(intent9);
							} else {
								Intent intent1111 = new Intent(getActivity(), RemoteAirActivity2.class);
								intent1111.putExtra("position", -1);
								intent1111.putExtra("id", id);
								intent1111.putExtra("deviceModel", model);
								startActivity(intent1111);
							}
						}
					}
				default:
					break;
				}
			}
		});
		// 计算导航栏高度
		// 根据导航栏高度 设置广告轮播版的高度
		myLinearLayout.setNavigationBarChangedListener(new NavigationBarChangedListener() {

			@Override
			public void show(boolean show) {
				// TODO Auto-generated method stub
				int navigationBarHeight = Util.getNavigationBarHeight(getActivity());
				LayoutParams params;
				if (show) {
					params = new LayoutParams(LayoutParams.MATCH_PARENT,
							mBrandLayout.getHeight() - navigationBarHeight);
					adapter = true;
				} else {
					params = new LayoutParams(LayoutParams.MATCH_PARENT,
							mBrandLayout.getHeight() + navigationBarHeight);
					adapter = false;
				}
				mBrandLayout.setLayoutParams(params);
			}
		});
	}

	private void checkNavigationBar() {
		if (getActivity() == null) {
			return;
		}
		int navigationBarHeight = Util.getNavigationBarHeight(getActivity());
		LayoutParams params;
		if ((!adapter) && Util.getNavigationBarShow(getActivity())) {
			params = new LayoutParams(LayoutParams.MATCH_PARENT, mBrandLayout.getHeight() - navigationBarHeight);
			mBrandLayout.setLayoutParams(params);
			adapter = true;
		} else {

		}
	}

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case GET_DEVICE_SUCCESS:
				mDevices = DeviceManager.getInstance().getAllDevice();
				if (mDevices.size() > 0) {
					mLoadingTv.setVisibility(View.GONE);
					empty_rl.setVisibility(View.GONE);
					layout1.setVisibility(View.VISIBLE);
					mRooms = DeviceManager.getInstance().getRooms();
					mScenes = DeviceManager.getInstance().getScenes();
					layout2.setVisibility(View.GONE);
					layout2Show = false;
					mStatusTv.setText("全局状态：          数量：" + mDevices.size() + " 在线：" + mDevices.size());
					getAllRooms();
				} else {
					mLoadingTv.setVisibility(View.GONE);
					empty_rl.setVisibility(View.VISIBLE);
					layout1.setVisibility(View.GONE);
					layout2.setVisibility(View.VISIBLE);
					layout2Show = true;
					mStatusTv.setText("全局状态：          数量：" + mDevices.size() + " 在线：" + mDevices.size());
				}
				break;
			case GET_DEVICE_FAIL:

				break;
			case GET_SCENE_SUCCESS:
				// 遍历场景 获取场景任务
				getAllTasks();
				break;
			case GET_ROOM_SUCCESS:
				getAllRoom();
				break;
			case GET_PERMISSION_SUCCESS:

				mScenes.get(msg.arg2).setSelect(!mScenes.get(msg.arg2).isSelect());
				String sceneId;
				switch (msg.arg1) {
				case 1:

					break;
				case 9:

					break;

				default:
					break;
				}
				break;
			case GET_SCENE_FINISH:
				if (mSvProgressHUD.isShowing()) {
					mSvProgressHUD.dismiss();
				}
				break;
			default:
				break;
			}
		}
	};

	private void initialize() {

		cycleViewPager = (CycleViewPager) getActivity().getFragmentManager()
				.findFragmentById(R.id.fragment_cycle_viewpager_content);

		for (int i = 0; i < imageUrls.length; i++) {
			ADInfo info = new ADInfo();
			info.setUrl(imageUrls[i]);
			info.setRes(imageRes[i]);
			info.setContent("图片-->" + i);
			infos.add(info);
		}

		// 将最后一个ImageView添加进来
		views.add(ViewFactory.getImageViewByResource(getActivity(), infos.get(infos.size() - 1).getRes()));
		for (int i = 0; i < infos.size(); i++) {
			views.add(ViewFactory.getImageViewByResource(getActivity(), infos.get(i).getRes()));
		}
		// 将第一个ImageView添加进来
		// views.add(ViewFactory.getImageView(getActivity(),
		// infos.get(0).getUrl()));
		views.add(ViewFactory.getImageViewByResource(getActivity(), infos.get(0).getRes()));
		// 设置循环，在调用setData方法前调用
		cycleViewPager.setCycle(true);

		// 在加载数据前设置是否循环
		cycleViewPager.setData(views, infos, mAdCycleViewListener);
		// 设置轮播
		cycleViewPager.setWheel(true);

		// 设置轮播时间，默认5000ms
		cycleViewPager.setTime(2000);
		// 设置圆点指示图标组居中显示，默认靠右
		cycleViewPager.setIndicatorCenter();
	}

	/**
	 * 配置ImageLoder
	 */
	private void configImageLoader() {
		// 初始化ImageLoader
		@SuppressWarnings("deprecation")
		DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.icon_stub) // 设置图片下载期间显示的图片
				.showImageForEmptyUri(R.drawable.icon_empty) // 设置图片Uri为空或是错误的时候显示的图片
				.showImageOnFail(R.drawable.icon_error) // 设置图片加载或解码过程中发生错误显示的图片
				.cacheInMemory(true) // 设置下载的图片是否缓存在内存中
				.cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
				// .displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片
				.build(); // 创建配置过得DisplayImageOption对象

		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity())
				.defaultDisplayImageOptions(options).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory().discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO).build();
		ImageLoader.getInstance().init(config);
	}

	private ImageCycleViewListener mAdCycleViewListener = new ImageCycleViewListener() {

		@Override
		public void onImageClick(ADInfo info, int position, View imageView) {
			if (cycleViewPager.isCycle()) {
				position = position - 1;

			}

		}

	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.scan_layout:
			// 检查版本
			// 检查权限
			// 如果没有权限 弹出提示 由于无法判断用户是否选了不再提示 所以直接每次都弹出提示框询问用户是否启用摄像头
			if (Build.VERSION.SDK_INT >= 23) {
				// boolean should = checkShould();
				// if (should) {
				// askPermission(Manifest.permission.CAMERA);
				// } else {
				if (ContextCompat.checkSelfPermission(getActivity(),
						Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
					// 不能使用 调用以下方法申请摄像头权限
					boolean should = checkShould(Manifest.permission.CAMERA);
					if (should) {
						askPermission(Manifest.permission.CAMERA);
					} else {
						MainFragment.this.requestPermissions(new String[] { Manifest.permission.CAMERA }, 0);
					}
					// 同时要弹出提示框提醒
					// askPermission(Manifest.permission.CAMERA);
				} else {
					Intent intent = new Intent(getActivity(), CaptureActivity.class);
					intent.putExtra("entry", 2);
					startActivity(intent);
				}
				// }
			} else {
				Intent intent = new Intent(getActivity(), CaptureActivity.class);
				intent.putExtra("entry", 2);
				startActivity(intent);
			}
			break;
		case R.id.share_layout:
			BlurBehind.getInstance().execute(getActivity(), new OnBlurCompleteListener() {
				@Override
				public void onBlurComplete() {
					Intent intent = new Intent(getActivity(), ShareTargetActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);

					startActivity(intent);
				}
			});
			break;
		case R.id.earn_layout:
			BlurBehind.getInstance().execute(getActivity(), new OnBlurCompleteListener() {
				@Override
				public void onBlurComplete() {
					Intent intent = new Intent(getActivity(), EarnMoneyActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
					startActivity(intent);
				}
			});
			break;
		case R.id.service_layout:
			// ToastShow.Show(getActivity(), "尚未实现");
			showTelDialog();
			break;
		case R.id.setting_btn:
			BlurBehind.getInstance().execute(getActivity(), new OnBlurCompleteListener() {
				@Override
				public void onBlurComplete() {
					Intent intent = new Intent(getActivity(), DeviceStateActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
					startActivity(intent);
				}
			});
			break;
		case R.id.tab_btn:
			if (isSceneShow) {
				mRoomC.setVisibility(View.VISIBLE);
				mSceneC.setVisibility(View.GONE);
				mTabBtn.setBackgroundResource(R.drawable.xx2x2);
				if (!mRoomC.getTopId().equals("-1")) {
					Log.i("wmy", "mRoomC.getTopId() = " + mRoomC.getTopId());
					if (DeviceManager.getInstance().getRoomById(mRoomC.getTopId()) != null) {
						List<Device> devices = DeviceManager.getInstance().getGroupChildDevicesById(mRoomC.getTopId());
						Log.i("wmy",
								"RoomName = " + DeviceManager.getInstance().getRoomById(mRoomC.getTopId()).getRoomName()
										+ " devices.size() = " + devices.size());
						for (int i = 0; i < devices.size(); i++) {
							Log.i("wmy", "devices.get(i).getDeviceName() = " + devices.get(i).getDeviceName());
						}
						mDeviceCircle.setDevices(devices);
					}
				} else {

				}
			} else {
				mSceneC.setVisibility(View.VISIBLE);
				mRoomC.setVisibility(View.GONE);
				mTabBtn.setBackgroundResource(R.drawable.xx2x1);
				if (!mSceneC.getTopId().equals("-1")) {
					Log.i("wmy", "mSceneC.getTopId() = " + mSceneC.getTopId());
					if (DeviceManager.getInstance().getSceneById(mSceneC.getTopId()) != null) {
						List<Device> devices = DeviceManager.getInstance().getSceneChildDevicesById(mSceneC.getTopId());
						mDeviceCircle.setDevices(devices);
					}
				}
			}
			isSceneShow = !isSceneShow;
			break;
		case R.id.get_free_btn:
			ToastShow.Show(getActivity(), "尚未完善");
			// Intent intent = new
			// Intent(getActivity(),FreeDeviceListActivity.class);
			// getActivity().startActivity(intent);
			break;
		case R.id.first_btn:
			// List<Order> orders = DeviceManager.getInstance().getOrders();
			// if (orders.size() != 0) {
			if (DeviceManager.getInstance().getCurrentOrder().getPublishUserName() != null) {
				Intent intent6 = new Intent(getActivity(), FirstSetupActivity1.class);
				getActivity().startActivity(intent6);
			} else {
				Intent intent6 = new Intent(getActivity(), PublishOrderActivity.class);
				intent6.putExtra("explain", "explain");
				startActivity(intent6);
				return;
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		// TODO Auto-generated method stub
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		Log.i("wmy", "权限确认结果 requestCode = " + requestCode + " permissions [0] = " + permissions[0] + " grantResults[0]"
				+ grantResults[0]);
		switch (requestCode) {
		case 0:
			if (permissions[0].equals(Manifest.permission.CAMERA)) {
				if (grantResults[0] == 0) {
					Intent intent = new Intent(getActivity(), CaptureActivity.class);
					intent.putExtra("entry", 2);
					startActivity(intent);
				} else {
					ToastShow.Show(getActivity(), "您已禁止使用相机，无法使用扫一扫功能");
				}
			} else if (permissions[0].equals(Manifest.permission.CALL_PHONE)) {
				if (grantResults[0] == 0) {
					Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:051282216666"));
					startActivity(intent);
				} else {
					ToastShow.Show(getActivity(), "您已禁止自动拨打客服电话，请记下该号码手动拨打");
				}
			}
			break;

		default:
			break;
		}
	}

	private void askPermission(String permission) {
		String request = "";
		if (permission.equals(Manifest.permission.CAMERA)) {
			request = "摄像头权限被禁止，是否开启摄像头？（点击“确定”跳转至应用信息界面，再进入“权限”选项即可进行设置）";
		} else if (permission.equals(Manifest.permission.CALL_PHONE)) {
			request = "拨打电话权限被禁止，是否开启该权限？（点击“确定”跳转至应用信息界面，再进入“权限”选项即可进行设置）";
		}
		mNormalDialog = new NormalDialog(getActivity());
		mNormalDialog.content(request).style(NormalDialog.STYLE_TWO)//
				.titleTextSize(18)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
			}
		}, new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
				Intent intent = new Intent();
				intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
				intent.setData(uri);
				startActivity(intent);
			}
		});
	}

	private void showTelDialog() {
		final Dialog dialog = new Dialog(getActivity(), R.style.DIYDialog);
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setContentView(R.layout.dialog_service);
		Button cancel_btn = (Button) dialog.findViewById(R.id.cancel_btn);
		Button ok_btn = (Button) dialog.findViewById(R.id.ok_btn);
		cancel_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		ok_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				if (Build.VERSION.SDK_INT >= 23) {
					if (ContextCompat.checkSelfPermission(getActivity(),
							Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
						boolean should = checkShould(Manifest.permission.CALL_PHONE);
						if (should) {
							askPermission(Manifest.permission.CALL_PHONE);
						} else {
							ActivityCompat.requestPermissions(getActivity(),
									new String[] { Manifest.permission.CALL_PHONE }, 0);
						}
					} else {
						Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:051282216666"));
						startActivity(intent);
					}
				} else {
					Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:051282216666"));
					startActivity(intent);
				}
			}
		});
		dialog.show();
	}

	public void showOpenSceneDialog(final String sceneId) {
		mNormalDialog = new NormalDialog(getActivity());
		mNormalDialog.content("是否打开该情景：" + DeviceManager.getInstance().getSceneById(sceneId).getSceneName() + "？")
				.style(NormalDialog.STYLE_TWO)//
				.titleTextSize(18)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
			}
		}, new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
				openScene1(sceneId,true);
				openScene2(sceneId);
			}
		});
	}

	public  void openScene1(String sceneId,boolean isdialogshow) {
		Scene s = DeviceManager.getInstance().getSceneById(sceneId);
		if(isdialogshow){
			mSvProgressHUD = new SVProgressHUD(getActivity());
			mSvProgressHUD.showWithStatus("正在开启：" + s.getSceneName());
		}
		int cmds = 0;
		for (int i = 0; i < s.getCloseCmds().size(); i++) {
			if (SocketManager.getInstance().sMap.get(s.getCloseCmds().get(i).getMainDeviceId()) != null) {
				if (s.getCloseCmds().get(i).getCloseCmdl().length() != 0) {
					cmds++;
					cmds++;
				}
				if (s.getCloseCmds().get(i).getCloseCmdss().length() != 0) {
					cmds++;
					cmds++;
				}
				if (s.getCloseCmds().get(i).getCloseCmdcurtain().length() != 0) {
					cmds++;
					cmds++;
				}
				if (s.getCloseCmds().get(i).getCloseCmdLingHuo().length() != 0) {
					cmds++;
					cmds++;
				}
				if (s.getCloseCmds().get(i).getCloseCmdLingHuo2().length() != 0) {
					cmds++;
					cmds++;
				}
				if (s.getCloseCmds().get(i).getCloseCmdLingHuo3().length() != 0) {
					cmds++;
					cmds++;
				}
				if (s.getCloseCmds().get(i).getIr_cmd().length() != 0) {
					cmds++;
				}
			}
		}
		for (int i = 0; i < s.getOpenCmds().size(); i++) {
			if (SocketManager.getInstance().sMap.get(s.getOpenCmds().get(i).getMainDeviceId()) != null) {
				if (s.getOpenCmds().get(i).getOpenCmdl().length() != 0) {
					cmds++;
					cmds++;
				}
				if (s.getOpenCmds().get(i).getOpenCmdss().length() != 0) {
					cmds++;
					cmds++;
				}
				if (s.getOpenCmds().get(i).getOpenCmdCurtain().length() != 0) {
					cmds++;
					cmds++;
				}
				if (s.getOpenCmds().get(i).getOpenCmdLinghuo().length() != 0) {
					cmds++;
					cmds++;
				}
				if (s.getOpenCmds().get(i).getOpenCmdLinghuo2().length() != 0) {
					cmds++;
					cmds++;
				}
				if (s.getOpenCmds().get(i).getOpenCmdLinghuo3().length() != 0) {
					cmds++;
					cmds++;
				}
				if (s.getOpenCmds().get(i).getIr_cmd().length() != 0) {
					cmds++;
				}
			}
		}
		checkFinish(cmds);
		Log.i("wmy", "点击了" + s.getScene_Tasks().size() + " " + s.getCloseCmds().size() + " " + s.getOpenCmds().size());
		for (int i = 0; i < s.getCloseCmds().size(); i++) {
			Log.i("wmy", "获取关指令" + i + " " + s.getCloseCmds().get(i).getIr_cmd());
			if (SocketManager.getInstance().sMap.get(s.getCloseCmds().get(i).getMainDeviceId()) != null) {
				if (s.getCloseCmds().get(i).getCloseCmdl().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getCloseCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getCloseCmds().get(i).getCloseCmdl());
				}
				if (s.getCloseCmds().get(i).getCloseCmdss().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getCloseCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getCloseCmds().get(i).getCloseCmdss());
				}
				if (s.getCloseCmds().get(i).getCloseCmdcurtain().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getCloseCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getCloseCmds().get(i).getCloseCmdcurtain());
				}
				if (s.getCloseCmds().get(i).getCloseCmdLingHuo().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getCloseCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getCloseCmds().get(i).getCloseCmdLingHuo());
				}
				if (s.getCloseCmds().get(i).getCloseCmdLingHuo2().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getCloseCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getCloseCmds().get(i).getCloseCmdLingHuo2());
				}
				if (s.getCloseCmds().get(i).getCloseCmdLingHuo3().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getCloseCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getCloseCmds().get(i).getCloseCmdLingHuo3());
				}
				if (s.getCloseCmds().get(i).getIr_cmd().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getCloseCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getCloseCmds().get(i).getIr_cmd());
					if (i < s.getCloseCmds().size()) {
						myDBHelper.updateStatusPower(s.getCloseCmds().get(i).getIr_deviceId(), 1);
					}
				}
			}
		}
		for (int i = 0; i < s.getOpenCmds().size(); i++) {
			Log.i("wmy",
					"获取开指令" + i + " " + s.getOpenCmds().get(i).getMainDeviceId() + " "
							+ s.getOpenCmds().get(i).getOpenCmdl() + " " + s.getOpenCmds().get(i).getOpenCmdss() + " "
							+ s.getOpenCmds().get(i).getIr_cmd());
			if (SocketManager.getInstance().sMap.get(s.getOpenCmds().get(i).getMainDeviceId()) != null) {
				if (s.getOpenCmds().get(i).getOpenCmdl().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getOpenCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getOpenCmds().get(i).getOpenCmdl());
				}
				if (s.getOpenCmds().get(i).getOpenCmdss().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getOpenCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getOpenCmds().get(i).getOpenCmdss());
				}
				if (s.getOpenCmds().get(i).getOpenCmdCurtain().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getOpenCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getOpenCmds().get(i).getOpenCmdCurtain());
				}
				if (s.getOpenCmds().get(i).getOpenCmdLinghuo().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getOpenCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getOpenCmds().get(i).getOpenCmdLinghuo());
				}
				if (s.getOpenCmds().get(i).getOpenCmdLinghuo2().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getOpenCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getOpenCmds().get(i).getOpenCmdLinghuo2());
				}
				if (s.getOpenCmds().get(i).getOpenCmdLinghuo3().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getOpenCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getOpenCmds().get(i).getOpenCmdLinghuo3());
				}
				if (s.getOpenCmds().get(i).getIr_cmd().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getOpenCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getOpenCmds().get(i).getIr_cmd());
					Log.e("wmy", "s.getOpenCmds() = " + s.getOpenCmds().size() + " i = " + i);
					if (i < s.getCloseCmds().size()) {
						myDBHelper.updateStatusPower(s.getOpenCmds().get(i).getIr_deviceId(), 0);
					}
				}
			}
		}
	}

	public void openScene2(String sceneId) {
		Log.i("wmy", "重发");
		Scene s = DeviceManager.getInstance().getSceneById(sceneId);
		for (int i = 0; i < s.getCloseCmds().size(); i++) {
			if (SocketManager.getInstance().sMap.get(s.getCloseCmds().get(i).getMainDeviceId()) != null) {
				if (s.getCloseCmds().get(i).getCloseCmdl().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getCloseCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getCloseCmds().get(i).getCloseCmdl());
				}
				if (s.getCloseCmds().get(i).getCloseCmdss().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getCloseCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getCloseCmds().get(i).getCloseCmdss());
				}
				if (s.getCloseCmds().get(i).getCloseCmdcurtain().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getCloseCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getCloseCmds().get(i).getCloseCmdcurtain());
				}

				if (s.getCloseCmds().get(i).getCloseCmdLingHuo().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getCloseCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getCloseCmds().get(i).getCloseCmdLingHuo());
				}
				if (s.getCloseCmds().get(i).getCloseCmdLingHuo2().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getCloseCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getCloseCmds().get(i).getCloseCmdLingHuo2());
				}
				if (s.getCloseCmds().get(i).getCloseCmdLingHuo3().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getCloseCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getCloseCmds().get(i).getCloseCmdLingHuo3());
				}
			}

		}
		for (int i = 0; i < s.getOpenCmds().size(); i++) {
			if (SocketManager.getInstance().sMap.get(s.getOpenCmds().get(i).getMainDeviceId()) != null) {
				if (s.getOpenCmds().get(i).getOpenCmdl().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getOpenCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getOpenCmds().get(i).getOpenCmdl());
				}
				if (s.getOpenCmds().get(i).getOpenCmdss().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getOpenCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getOpenCmds().get(i).getOpenCmdss());
				}
				if (s.getOpenCmds().get(i).getOpenCmdCurtain().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getOpenCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getOpenCmds().get(i).getOpenCmdCurtain());
				}
				if (s.getOpenCmds().get(i).getOpenCmdLinghuo().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getOpenCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getOpenCmds().get(i).getOpenCmdLinghuo());
				}
				if (s.getOpenCmds().get(i).getOpenCmdLinghuo2().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getOpenCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getOpenCmds().get(i).getOpenCmdLinghuo2());
				}
				if (s.getOpenCmds().get(i).getOpenCmdLinghuo3().length() != 0) {
					SocketManager.getInstance().sMap.get(s.getOpenCmds().get(i).getMainDeviceId())
							.sendMqttDataDelay(s.getOpenCmds().get(i).getOpenCmdLinghuo3());
				}
			}
		}
	}

	private void checkFinish(int cmds) {
		int delay = 0;
		if (cmds > 1) {
			delay = cmds * 1000;
		} else {
			delay = 1000;
		}
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				mHandler.sendEmptyMessage(GET_SCENE_FINISH);
			}
		}, delay);
	}

	public void getAllScene() {
		if (NetUtil.isNetworkAvailable(getActivity())) {
			if (!Util.isLogin(getActivity())) {
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_SCENE_LIST);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("hid", DeviceManager.getInstance().hid);
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getActivity(), "token", ""));
				// Log.d("test", " get all scene = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					// Log.e("wmy", "get all scene=" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							DeviceManager.getInstance().clearScene();
							JSONObject data = jsonObject.getJSONObject("data");
							JSONArray ja = data.getJSONArray("lscene");
							// Log.e("wmy", "length " + ja.length());
							if (data.length() != 0) {
								for (int i = 0; i < ja.length(); i++) {
									String sceneId = ja.getJSONObject(i).getString("sceneId");
									String userId = ja.getJSONObject(i).getString("userId");
									String sceneName = ja.getJSONObject(i).getString("sceneName");
									long createTime = ja.getJSONObject(i).getLong("createTime");
									int status = ja.getJSONObject(i).getInt("status");
									String hid = ja.getJSONObject(i).getString("hid");
									Scene scene = new Scene(sceneId, userId, sceneName, status, hid);
									DeviceManager.getInstance().addScene(scene);
								}
							}

							Message msg = Message.obtain();
							msg.what = GET_SCENE_SUCCESS;
							mHandler.sendMessage(msg);

						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							Toast.makeText(getActivity(), "您的登陆已超时，请重新登陆", Toast.LENGTH_SHORT).show();
							startActivity(new Intent(getActivity(), LoginActivity.class));
							getActivity().finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {

				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

	public void getAllDevice() {
		if (NetUtil.isNetworkAvailable(getActivity())) {
			if (!Util.isLogin(getActivity())) {
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_DEVICE_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("hid", DeviceManager.getInstance().hid);
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getActivity(), "token", ""));
				Log.e("wmy", " get all device = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					// Log.e("wmy", "get all device fragment =" + result);
					// Dev
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							JSONArray data = jsonObject.getJSONArray("data");
							// Log.e("wmy", "length " + data.length());
							if (data.length() != 0) {
								for (int i = 0; i < data.length(); i++) {
									JSONObject deviceInfo = data.getJSONObject(i).getJSONObject("deviceInfo");
									String deviceId = deviceInfo.getString("deviceId");
									String deviceWifiSSID = deviceInfo.getString("deviceWifiSSID");
									String deviceAddress = deviceInfo.optString("deviceAddress");
									int deviceType = deviceInfo.getInt("deviceType");
									String deviceModel = deviceInfo.getString("deviceModel");
									String deviceName = data.getJSONObject(i).getString("remarks");// deviceName
									int status = deviceInfo.optInt("deviceStatus");
									int role = data.getJSONObject(i).optInt("role");
									String userId = deviceInfo.getString("userId");
									String mainDeviceId = deviceInfo.optString("mainDeviceId");
									Device device = new Device();
									device.setDeviceID(deviceId);
									device.setDeviceWifiSsid(deviceWifiSSID);
									device.setDeviceType(deviceType);
									device.setDeviceBrand(deviceModel);
									device.setDeviceName(deviceName);
									device.setStatus(status);
									device.setRole(role);
									device.setUserId(userId);
									if (deviceType == DeviceType.DEVICE_TYPE_AIR_CONTROLLER
											|| deviceType == DeviceType.DEVICE_TYPE_BOX2
											|| deviceType == DeviceType.DEVICE_TYPE_DVD
											|| deviceType == DeviceType.DEVICE_TYPE_FAN
											|| deviceType == DeviceType.DEVICE_TYPE_TV
											|| deviceType == DeviceType.DEVICE_TYPE_PROJECTOR) {
										// 是遥控器
										JSONArray ja = data.getJSONObject(i).getJSONArray("deviceButton");
										List<Key> keys = new ArrayList<Key>();
										for (int n = 0; n < ja.length(); n++) {
											Key key = new Key();
											JSONObject joKey = ja.getJSONObject(n);
											key.setKeyNum(joKey.getInt("position"));
											key.setCodeValue(joKey.getString("buttonCmd"));
											keys.add(key);
										}
										device.setKeys(keys);
									}
									if (deviceType != DeviceType.DEVICE_TYPE_WLAN) {
										device.setMainDeviceId(mainDeviceId);
									} else {
										device.setMainDeviceId(deviceId);
									}
									device.setDeviceAddress(deviceAddress);
									DeviceManager.getInstance().addDevice(device);
									myDBHelper.addStatus(deviceId, false, 0, 0, 0);
									device = null;
								}
							}
							List<String> nullMids = Util.checkNull();
							if (nullMids.size() == 0) {
								Log.e("wmy", "1118获取全部设备 没有需要重新获取的mid");
								Message msg = Message.obtain();
								msg.what = GET_DEVICE_SUCCESS;
								mHandler.sendMessage(msg);
							} else {
								Log.e("wmy", "1123获取全部设备 有需要重新获取的mid");
								getNullWlan(nullMids);
							}
						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							Toast.makeText(getActivity(), "您的登陆已超时，请重新登陆", Toast.LENGTH_SHORT).show();
							startActivity(new Intent(getActivity(), LoginActivity.class));
							getActivity().finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

	public void getNullWlan(List<String> mids) {
		for (int i = 0; i < mids.size(); i++) {
			getWlanInfo(mids.get(i));
		}
	}

	private void getWlanInfo(String mid) {
		if (NetUtil.isNetworkAvailable(getActivity())) {
			if (!Util.isLogin(getActivity())) {
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_WLAN_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("deviceId", mid);
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getActivity(), "token", ""));
				Log.e("wmy", " get single wlan = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					// Log.e("wmy", "get all device fragment =" + result);
					// Dev
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							JSONObject deviceInfo = jsonObject.getJSONObject("data");
							String deviceId = deviceInfo.getString("deviceId");
							String deviceWifiSSID = deviceInfo.getString("deviceWifiSSID");
							String deviceAddress = deviceInfo.optString("deviceAddress");
							int deviceType = deviceInfo.getInt("deviceType");
							String deviceModel = deviceInfo.getString("deviceModel");
							String deviceName = deviceInfo.optString("remarks");// deviceName
							int status = deviceInfo.optInt("deviceStatus");
							int role = deviceInfo.optInt("role");
							String userId = deviceInfo.getString("userId");
							String mainDeviceId = deviceInfo.optString("mainDeviceId");
							Device device = new Device();
							device.setDeviceID(deviceId);
							device.setDeviceWifiSsid(deviceWifiSSID);
							device.setDeviceType(deviceType);
							device.setDeviceBrand(deviceModel);
							device.setDeviceName(deviceName);
							device.setStatus(status);
							device.setRole(role);
							device.setUserId(userId);
							if (deviceType != DeviceType.DEVICE_TYPE_WLAN) {
								device.setMainDeviceId(mainDeviceId);
							} else {
								device.setMainDeviceId(deviceId);
							}
							device.setDeviceAddress(deviceAddress);
							DeviceManager.getInstance().addDevice(device);
							device = null;

							Log.e("wmy", "1118获取全部设备 没有需要重新获取的mid");
							Message msg = Message.obtain();
							msg.what = GET_DEVICE_SUCCESS;
							mHandler.sendMessage(msg);

						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							Toast.makeText(getActivity(), "您的登陆已超时，请重新登陆", Toast.LENGTH_SHORT).show();
							startActivity(new Intent(getActivity(), LoginActivity.class));
							getActivity().finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

	public void getAllRooms() {
		if (NetUtil.isNetworkAvailable(getActivity())) {
			RequestParams params = new RequestParams(HttpURL.GET_ROOM_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("hid", DeviceManager.getInstance().hid);
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getActivity(), "token", ""));
				// Log.e("test", " get all rooms obj = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					DeviceManager.getInstance().clearRoom();
					// Log.e("wmy", "get all room = " + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							JSONArray data = jsonObject.getJSONArray("data");
							if (data.length() != 0) {
								for (int i = 0; i < data.length(); i++) {
									JSONObject jo = data.getJSONObject(i);
									String roomId = jo.getString("roomId");
									String roomName = jo.optString("roomName");
									List<Device> deviceses = new ArrayList<Device>();
									JSONArray ja = jo.getJSONArray("deviceses");
									for (int j = 0; j < ja.length(); j++) {
										int deviceType = ja.getJSONObject(j).getInt("deviceType");
										String deviceId = ja.getJSONObject(j).getString("deviceId");// deviceName
										String deviceMac = ja.getJSONObject(j).optString("deviceMac");
										int status = ja.getJSONObject(j).getInt("nurdStatus");
										// String userId =
										String deviceName = ja.getJSONObject(j).getString("remarks");
										Device device = new Device(deviceId, deviceMac, deviceName, deviceType, status);
										device.setDeviceAddress(deviceMac);
										deviceses.add(device);
									}
									// Log.i("room", "新增一个room " + roomName);
									Room room = new Room(roomId, roomName, deviceses);
									Log.e("room", roomId + " 组别ID 添加设备 " + deviceses.size());
									DeviceManager.getInstance().setGroupChildDevices(roomId, deviceses);
									// Log.i("wmy", "925");
									DeviceManager.getInstance().addRoom(room);
									// Log.i("wmy", "927");
									if (i == (data.length() - 1)) {
										Message msg = Message.obtain();
										msg.what = GET_ROOM_SUCCESS;
										mHandler.sendMessage(msg);
										// Log.i("wmy", "931发送 GET_ROOM_SUCCESS"
										// + System.currentTimeMillis());
									}
								}
							}
							Message msg = Message.obtain();
							msg.what = GET_ROOM_SUCCESS;
							mHandler.sendMessage(msg);
							Log.i("wmy", "938发送 GET_ROOM_SUCCESS" + System.currentTimeMillis());
						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							// Toast.makeText(getActivity(), "您的登陆已超时，请重新登陆",
							// Toast.LENGTH_SHORT).show();
							// startActivity(new Intent(getActivity(),
							// LoginActivity.class));
							// getActivity().finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

	private void getAllRoom() {
		mRooms = DeviceManager.getInstance().getRooms();
		// 打开APP时，第一次请求组别数据，有时候DeviceManager里的roomMap会没有cmds的数据
		// 在这里做一次添加 权宜之计
		// if (MainActivity.mainActivity.start) {
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				for (int i = 0; i < mRooms.size(); i++) {
					DeviceManager.getInstance().putRoomInMap(mRooms.get(i));
				}
			}
		}, 2 * 1000);
		// }
		mRoomC.setRooms(mRooms);
	}

	private void getAllTasks() {
		mScenes = DeviceManager.getInstance().getScenes();
		mSceneC.setScenes(mScenes);
		for (int i = 0; i < mScenes.size(); i++) {
			getTaskBySceneId(i, mScenes.get(i).getSceneId());
		}
		// 延迟1秒执行 如果mScenes不为空 则一秒后根据sceneId获取scene的设备集合 将设备集合加载至外圈
		// if (mScenes.size() != 0) {
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (isSceneShow) {
					if (mScenes.size() > 0) {
						String id = mScenes.get(0).getSceneId();
						List<Device> devices = DeviceManager.getInstance().getSceneById(id).getDevices();
						mDeviceCircle.setDevices(devices);
					} else {

						List<Device> devices = new ArrayList<Device>();
						mDeviceCircle.setDevices(devices);
					}
				} else {
					if (mRooms.size() > 0) {
						String id = mRooms.get(0).getRoomId();
						List<Device> devices = DeviceManager.getInstance().getRoomById(id).getDevices();
						mDeviceCircle.setDevices(devices);
					} else {
						List<Device> devices = new ArrayList<Device>();
						mDeviceCircle.setDevices(devices);
					}
				}
			}
		}, 1 * 1000);
		// }
	}

	private void getTaskBySceneId(final int pos, final String sceneId) {
		if (NetUtil.isNetworkAvailable(getActivity())) {
			if (!Util.isLogin(getActivity())) {
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_SCENE_TASK_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("id", sceneId);
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getActivity(), "token", ""));
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("wmy", "get scene task =" + sceneId + " " + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							JSONArray data = jsonObject.getJSONArray("data");
							DeviceManager.getInstance().getSceneById(sceneId).clearTask();
							if (data.length() != 0) {
								// DeviceManager.getInstance().clearTask();
								List<Device> childDevices = new ArrayList<Device>();
								List<Scene_Task> tasks = new ArrayList<Scene_Task>();
								String sId = null;
								for (int i = 0; i < data.length(); i++) {
									JSONObject jo = data.getJSONObject(i);
									String stId = jo.getString("stId");
									String cmd = jo.getString("cmd");
									String cmdName = jo.getString("cmdName");
								//	String cmdName=cmdName1.split("\\|")[0];
									//String deviceName=cmdName1.split("\\|")[1];
									String did = jo.getString("did");
									Device device = DeviceManager.getInstance().getDeviceById(did);
									boolean e = false;
									for (Device d : childDevices) {
										if (d.getDeviceID().equals(device.getDeviceID())) {
											e = true;
										}
									}
									if (!e) {
										childDevices.add(device);
									}
									sId = jo.getString("sceneId");
									int delayed = jo.getInt("delayed");
									int hour = delayed / 3600;
									int min = delayed / 60;
									int sec = delayed % 60;
									Scene_Task task = new Scene_Task(stId, delayed, did, cmd, sId, cmdName, hour, min,
											sec, device.getMainDeviceId());
									tasks.add(task);
									DeviceManager.getInstance().addTask(task);
									Log.e("wmy", "1317 tasks.size() = " + tasks.size());
								}
								DeviceManager.getInstance().getSceneById(sceneId).setDevices(childDevices);
								DeviceManager.getInstance().getSceneById(sceneId).setScene_Tasks(tasks);
								DeviceManager.getInstance().setSceneChildDevices(sceneId, childDevices);
								DeviceManager.getInstance().getScenes().get(pos).setDevices(childDevices);
								// sceneChildDevicesMap.put(sceneId,
								// childDevices);
							}

							Message msg = Message.obtain();
							msg.what = GET_DEVICE_SUCCESS;
							mHandler.sendMessage(msg);

						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							Toast.makeText(getActivity(), "您的登陆已超时，请重新登陆", Toast.LENGTH_SHORT).show();
							startActivity(new Intent(getActivity(), LoginActivity.class));
							getActivity().finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}

	}

	private boolean checkShould(String permission) {
		if (shouldShowRequestPermissionRationale(permission)) {
			Log.e("permission", "未被禁用");
			return true;
		} else {
			Log.e("permission", "已被禁用");
			return false;
		}
	}


}
